package com.illtamer.infinite.collapsar.server.smtp;

import com.illtamer.infinite.collapsar.server.handler.Handler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringEscapeUtils;

public class SMTPServerHandler extends SimpleChannelInboundHandler<String> {

    private final TransferContext context = new TransferContext();

    private final Handler dataHandler = new DataHandler(context);

    private final Handler commandHandler = new SMTPCommandHandler(context);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        // 与客户端成功建立连接，并回复状态
        channel.writeAndFlush("220\r\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        Channel channel = ctx.channel();
        System.out.println("接收指令：" + StringEscapeUtils.unescapeJava(msg));
        if (context.isFinishData())
            dataHandler.handle(msg, channel);
        else
            commandHandler.handle(msg, channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.channel().close();
    }

}
